package com.konsung.ksdc.manager.community;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.SpannableString;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.j256.ormlite.dao.RuntimeExceptionDao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
import com.j256.ormlite.stmt.Where;
import com.konsung.ksdc.R;
import com.konsung.ksdc.bean.MqttMsgBean;
import com.konsung.ksdc.bean.MqttMsgNotice;
import com.konsung.ksdc.bean.netbean.RegisterUserNetBean;
import com.konsung.ksdc.common.database.DatabaseHelper;
import com.konsung.ksdc.common.mqtt.KsdcMqttClient;
import com.konsung.ksdc.common.mqtt.MqttMsgUtils;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.utils.BroadCastActions;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.DateUtils;
import com.konsung.ksdc.common.utils.DensityUtils;
import com.konsung.ksdc.common.utils.EmojiUtils;
import com.konsung.ksdc.common.utils.FileUtils;
import com.konsung.ksdc.common.utils.ImageUtils;
import com.konsung.ksdc.common.utils.JsonUtils;
import com.konsung.ksdc.common.utils.PhotoUtils;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.common.utils.ToastUtils;
import com.konsung.ksdc.common.widget.TakePicBottomPop;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.machine.PicViewActivity;
import com.konsung.ksdc.service.MqttService;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.header.MaterialHeader;

/**
 * 创建者     kgh
 * 创建时间   2016/5/16 16:34
 * 描述  聊天界面
 * 更新者     $Author$
 * 更新时间   $Date$
 * 更新描述   ${TODO}
 */
public class ChatActivity extends Activity implements BroadCastActions {
    @Bind(R.id.ll_msg_container)
    LinearLayout llMsgContainer;
    @Bind(R.id.sv_msg_container)
    ScrollView svMsgContainer;
    private static final int VOICE = 3;
    private static final int PIC = 2;
    private static final int TEXT = 1;
    @Bind(R.id.btn_send_msg)
    Button btnSendMsg; // 发送按钮
    @Bind(R.id.et_msg)
    EditText etMsg; // 消息文本框
    @Bind(R.id.img_voice)
    ImageView imgVoice;
    @Bind(R.id.img_emoji)
    ImageView imgEmoji;
    @Bind(R.id.img_more)
    ImageView imgMore;
    @Bind(R.id.txt_contact_nick_name)
    TextView txtContactNickName;
    @Bind(R.id.ll_face_container)
    LinearLayout llFaceContainer;
    @Bind(R.id.btn_voice)
    Button btnVoice;
    @Bind(R.id.gv_emoji)
    GridView gvEmoji;
    @Bind(R.id.img_back)
    ImageView imgBack;
    @Bind(R.id.img_contact_msg)
    ImageView imgContactMsg;
    @Bind(R.id.ptr_resflsh)
    protected PtrFrameLayout ptrFrameLayout;
    @Bind(R.id.tv_count_down)
    TextView tvCountDown;

    public static final String PIC_FILE = "picFile";
    private String contactUserId;
    private String contactTopicName;
    private String contactNickName;
    private String contactPicPath;
    private String data;

    // 最后一次发送/接收时间标识
    private long lastTimeFlag = new Date().getTime();

    private TakePicBottomPop mPopWindom;
    private Uri imageUri;
    public static final int TAKE_PHOTO = 1;
    public static final int CROP_PHOTO = 2;
    public static final int SELECT_PIC = 3;
    private KsdcMqttClient mqttClient;
    private ArrayList<Bitmap> bitmapArrayList = new ArrayList<>();
    private int searchIndex; // 分页页码
    private int insertIndex = 0; // 消息区插入位置

    private Timer animationTimer = null; // 语音动画控制器
    private TimerTask timerTask = null; // 语音动画控制任务
    private int index = 1; // 记录语音动画图片
    AudioAnimationHandler audioAnimationHandler = null;
    private int currentId; // 记录正在播放的语音消息id
    private MediaPlayer mediaPlayer;
    private Timer maxTimer; // 录音限时控制器
    private TimerTask maxTimerTask; // 录音限时控制任务
    private int timeIndex = 0; //记录录音时间
    private int countDown = 5; // 录音时限倒计时

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        ButterKnife.bind(this);
        // 初始化组件
        initComponent();
        // 初始化MQTT回调
        initMessageCallback();
        // 启动activity时不自动弹出软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        initPtr();
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.e("ChatActivity", "onPause....");
        if (null != mediaPlayer && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer = null;
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.e("ChatActivity", "onRestart....");
    }

    @Override
    protected void onResume() {
        super.onResume();
        reloadHistoryMsg();
        Log.e("ChatActivity", "onResume....");
    }

    /**
     * 重新加载聊天记录
     */
    private void reloadHistoryMsg() {
        insertIndex = 0;
        searchIndex = 0;
        llMsgContainer.removeAllViews();
        initHistoryMsg();
        updateNoticeReadState();
    }

    /**
     * 初始化聊天记录
     */
    private void initComponent() {
        EmojiUtils.init();

        this.contactUserId = getIntent().getStringExtra("userId");
        this.contactTopicName = getIntent().getStringExtra("topicName");
        this.contactNickName = getIntent().getStringExtra("nickName");
        this.contactPicPath = getIntent().getStringExtra("picPath");
        this.data = getIntent().getStringExtra("data");
        this.txtContactNickName.setText(contactNickName);
        mSensor = new SoundMeter();

        // 绑定发送图片按钮
        this.bindImgMoreEvent();
        // 绑定语音事件
        this.bindBtnVoiceEvent();
        // 绑定发送按钮事件
        this.bindSendMsgButtonEvent();
        // 初始化历史消息
        this.initHistoryMsg();
        // 修改消息提醒状态
        this.updateNoticeReadState();
        // 表情按钮事件
        this.bindEmojiEvent();
        // 绑定后退按钮事件
        this.bindImgBackEvent();
        // 绑定好友资料按钮事件
        this.bindImgContactMsgEvent();
        // 绑定消息区滚动加载事件
        this.bindScrollLoadEvent();
    }

    /**
     * 初始化消息区滚动加载事件
     */
    private void bindScrollLoadEvent() {
        //  //当点击消息界面，表情界面消失
        svMsgContainer.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_MOVE:
                        break;

                    case MotionEvent.ACTION_DOWN:
                        llFaceContainer.setVisibility(View.GONE);
                        break;

                    case MotionEvent.ACTION_UP:
                        break;

                    default:
                        break;
                }
                return false;
            }
        });
    }

    /**
     * 刷新数据
     */
    private void initPtr() {
        /**
         * 谷歌刷新风格
         */
        final MaterialHeader header = new MaterialHeader(this);
        header.setBackgroundResource(R.color.refresh_bg);
        int[] colors = getResources().getIntArray(R.array.google_colors);
        header.setColorSchemeColors(colors);
        header.setPadding(0, DensityUtils.dp2px(this, 15), 0, 0);
        header.setPtrFrameLayout(ptrFrameLayout);
        ptrFrameLayout.setHeaderView(header);
        ptrFrameLayout.addPtrUIHandler(header);
        ptrFrameLayout.setPtrHandler(new PtrHandler() {

            //需要加载数据时触发
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                ptrFrameLayout.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //刷新数据
                        loadMsgData();
                        svMsgContainer.post(new Runnable() {
                            @Override
                            public void run() {
                                svMsgContainer.scrollTo(0, llMsgContainer.getTop());
                            }
                        });
                    }
                }, 1800);
            }

            /**
             * 检查是否可以执行下来刷新，比如列表为空或者列表第一项在最上面时。
             */
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                // 默认实现，根据实际情况做改动
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
            }
        });
    }

    /**
     * 加载聊天记录
     */
    private void loadMsgData() {
        // 开始处理每一条消息记录
        List<MqttMsgBean> historyMsgs = fetchMqttMessages(searchIndex);
        if (historyMsgs.isEmpty()) {
            //刷新停止
            ptrFrameLayout.refreshComplete();
            return;
        }
        //刷新停止
        ptrFrameLayout.refreshComplete();
        Collections.reverse(historyMsgs);

        // 叠加页码
        searchIndex++;

        insertIndex = 0;
        for (int i = 0; i < historyMsgs.size(); i++) {
            MqttMsgBean bean = historyMsgs.get(i);
            long time = 0;
            try {
                time = DateUtils.getDateFormat(bean.getMsgSendDate(),
                        DateUtils.yyyyMMddHHmmss).getTime();
            } catch (Exception e) {
                e.printStackTrace();
            }

            // 添加时间线
            addTimeLine(time, insertIndex);
            lastTimeFlag = time;

            if (bean.getContact().equals(NetConfig.currentUser.getUserId())) {
                // 添加当前用户消息
                addMyMsgToForeground(bean, insertIndex);
            } else {
                // 添加好友消息
                addContactMsg(bean, insertIndex);
            }
        }
    }

    /**
     * 好友资料按钮事件
     */
    private void bindImgContactMsgEvent() {
        imgContactMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ChatActivity.this, ContactIndexActivity.class);
                intent.putExtra("data", data);
                intent.putExtra(ContactIndexActivity.TYPE, ContactIndexActivity.TYPE_ONE);
                startActivity(intent);
            }
        });
    }

    /**
     * 后退按钮事件
     */
    private void bindImgBackEvent() {
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ChatActivity.this.finish();
            }
        });
    }

    /**
     * 绑定更多的事件
     */
    private void bindImgMoreEvent() {
        imgMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //判断软键盘是否开启
                hideInputWindow();
                addPhoto();
            }
        });
    }

    /**
     * 隐藏软键盘
     */
    public void hideInputWindow() {

        final View v = getWindow().peekDecorView();
        if (v != null && v.getWindowToken() != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(this
                    .INPUT_METHOD_SERVICE);
            if (imm.isActive()) {
                //隐藏软键盘
                imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
            }
        }
    }

    /**
     * 绑定表情按钮事件
     */
    private void bindEmojiEvent() {
        EmojiGridAdapter adapter = new EmojiGridAdapter(this);
        gvEmoji.setAdapter(adapter);
        gvEmoji.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,
                    int position, long l) {
                String key = EmojiUtils.emojiKeys.get(position);
                etMsg.setText(etMsg.getText() + key);
                etMsg.setSelection(etMsg.getText().length());
                llFaceContainer.setVisibility(View.GONE);
            }
        });
        this.imgEmoji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                llFaceContainer.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 点击添加图片，弹出popwindow。选择图库或拍照的图片。
     */
    private void addPhoto() {
        mPopWindom = new TakePicBottomPop(ChatActivity.this, itemsOnClick);
        mPopWindom.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });
        mPopWindom.showAtLocation(ChatActivity.this.etMsg,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    sendPicture(imageUri.getEncodedPath());
                }
                break;

            case CROP_PHOTO:
                try {
                    if (resultCode == RESULT_OK) {
                        sendPicture(imageUri.getEncodedPath());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case SELECT_PIC:
                if (resultCode == RESULT_OK) {
                    sendPicture(PhotoUtils.getPath(this, data.getData()));
                }
                break;
            default:
                break;
        }
    }

    /**
     * 发送图片
     * @param path 图片路径
     */
    private void sendPicture(String path) {
        String msgSendDate = DateUtils.getStringDateFormat(new
                Date(), DateUtils.yyyyMMddHHmmss);
        String targetType = MqttMsgUtils.MSG_TARGET_TYPE_PERSONAL;
        MqttMsgBean bean = new MqttMsgBean();
        bean.setMsgContent(path);
        bean.setMsgSendDate(msgSendDate);
        bean.setMsgTargetType(targetType);
        bean.setMsgType(MqttMsgUtils.MSG_TYPE_PIC);
        bean.setContact(NetConfig.currentUser.getUserId());
        bean.setTopicName(contactTopicName);

        // 显示图片到消息区
        sendMsg(bean, PIC);
    }

    private View.OnClickListener itemsOnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mPopWindom.dismiss();
            switch (v.getId()) {
                case R.id.btn_take_photo:
                    // 照相
                    clickTakePhoto();
                    break;
                case R.id.btn_album:
                    // 相册
                    clickAlbum();
                    break;
                case R.id.btn_cancel:
                    mPopWindom.dismiss();
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 点击相册（图库）
     */
    private void clickAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
        intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_PIC);
    }

    /**
     * 点击拍照
     */
    private void clickTakePhoto() {
        File outputImage = new File(Environment
                .getExternalStorageDirectory(), "test" + System.currentTimeMillis() + ".jpg");
        try {
            if (outputImage.exists()) {
                outputImage.delete();
            }
            outputImage.createNewFile();
        } catch (Exception e) {
            e.printStackTrace();
        }
        imageUri = Uri.fromFile(outputImage);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(intent, TAKE_PHOTO); // 启动相机程序
    }

    /**
     * 初始化历史消息，默认加载最新的10条
     */
    private void initHistoryMsg() {
        // 开始处理每一条消息记录,初始化0
        List<MqttMsgBean> historyMsgs = fetchMqttMessages(0);
        if (historyMsgs.isEmpty()) {
            return;
        }
        searchIndex++; // 叠加页码

        Collections.reverse(historyMsgs);

        for (MqttMsgBean bean : historyMsgs) {
            long time = 0;
            try {
                time = DateUtils.getDateFormat(bean.getMsgSendDate(),
                        DateUtils.yyyyMMddHHmmss).getTime();
            } catch (Exception e) {
                e.printStackTrace();
            }

            addTimeLine(time);
            lastTimeFlag = time;

            if (bean.getContact().equals(NetConfig.currentUser.getUserId())) {
                // 添加当前用户消息
                addMyMsgToForeground(bean);
            } else {
                // 添加好友消息
                addContactMsg(bean);
            }
        }
    }

    /**
     * 分页查询消息记录，取最新记录
     * @param index 索引
     * @return 消息记录
     */
    private List<MqttMsgBean> fetchMqttMessages(int index) {
        RuntimeExceptionDao dao = DatabaseHelper.getHelper(ChatActivity.this)
                .getRuntimeExceptionDao(MqttMsgBean.class);
        QueryBuilder qb = dao.queryBuilder();

        try {
            Where where = qb.where();
            Where exp1 = where.eq("topicName", contactTopicName);
            Where exp2 = where.eq("topicName", NetConfig.currentUser
                    .getUserName()).and().eq("contact", contactUserId);
            Where expOr = where.or(exp1, exp2);
            where.and(where.eq("ownerUserId",
                    NetConfig.currentUser.getUserId()), expOr);
            qb.orderBy("msgId", false);
            qb.limit(10L);
            qb.offset(10L * index);
            // 开始处理每一条消息记录
            return qb.query();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ArrayList<MqttMsgBean>();
    }

    /**
     * 更新消息收取状态
     */
    private void updateNoticeReadState() {
        // 标记消息提醒已读
        RuntimeExceptionDao noticeDao = DatabaseHelper.getHelper(ChatActivity.this)
                .getRuntimeExceptionDao(MqttMsgNotice.class);
        UpdateBuilder ub = noticeDao.updateBuilder();
        try {
            ub.where().eq("topicName", contactUserId).and().eq("ownerUserId",
                    NetConfig.currentUser.getUserId());
            ub.updateColumnValue("isRead", "Y");
            ub.update();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加好友消息到消息区
     * @param mqttMsg 消息
     * @param index 索引
     */
    private void addContactMsg(MqttMsgBean mqttMsg, int index) {
        if (MqttMsgUtils.MSG_TYPE_TXT.equals(mqttMsg.getMsgType())) {
            addContactTextMsgView(mqttMsg, index);
        } else if (MqttMsgUtils.MSG_TYPE_PIC.equals(mqttMsg.getMsgType())) {
            addContactPicMsgView(mqttMsg.getMsgContent(), index);
        } else if (MqttMsgUtils.MSG_TYPE_VOICE.equals(mqttMsg.getMsgType())) {
            addContactVoiceMsgView(mqttMsg, index);
        } else {
            Log.e("ChatActivity", "未知的协议类型...");
        }
        svMsgContainer.post(new Runnable() {
            @Override
            public void run() {
                svMsgContainer.scrollTo(0, llMsgContainer.getBottom());
            }
        });
        insertIndex++;
    }

    /**
     * 添加好友消息到消息区底部
     * @param mqttMsg 消息数据
     */
    private void addContactMsg(MqttMsgBean mqttMsg) {
        addContactMsg(mqttMsg, -1);
    }

    /**
     * 添加当前用户消息到消息区
     * @param mqttMsg 消息
     * @param index 索引
     */
    private void addMyMsgToForeground(MqttMsgBean mqttMsg, int index) {
        if (MqttMsgUtils.MSG_TYPE_TXT.equals(mqttMsg.getMsgType())) {
            addMyTextMsgView(mqttMsg.getMsgContent(), index);
        } else if (MqttMsgUtils.MSG_TYPE_PIC.equals(mqttMsg.getMsgType())) {
            addMyPicMsgView(mqttMsg.getMsgContent(), index);
        } else if (MqttMsgUtils.MSG_TYPE_VOICE.equals(mqttMsg.getMsgType())) {
            addMyVoiceMsgView(mqttMsg, index);
        } else {
            Log.e("ChatActivity", "未知的协议类型...");
            return;
        }
        svMsgContainer.post(new Runnable() {
            @Override
            public void run() {
                svMsgContainer.scrollTo(0, llMsgContainer.getBottom());
            }
        });
        insertIndex++;
    }

    /**
     * 添加当前用户消息到消息区底部
     * @param mqttMsg 消息
     */
    private void addMyMsgToForeground(MqttMsgBean mqttMsg) {
        addMyMsgToForeground(mqttMsg, -1);
    }

    /**
     * 添加语音消息到消息区
     * @param bean 消息
     * @param index 索引 -1代表最新的显示出来 非-1代表刷新的数据
     */
    private void addMyVoiceMsgView(final MqttMsgBean bean, int index) {
        View voiceContainer = getLayoutInflater().inflate(R.layout
                .view_msg_voice_me, null);

        // 头像
        ImageView imgPic = (ImageView) voiceContainer
                .findViewById(R.id.img_me_pic);
        TextView tvTimeCount = (TextView) voiceContainer.findViewById(R.id.tv_time_count);
        LinearLayout llMsgView = (LinearLayout) voiceContainer.findViewById(R.id.ll_msg_view);
        final ImageView ivAnimation = (ImageView) voiceContainer.findViewById(R.id.iv_animation);
        tvTimeCount.setText(getVoiceTime(bean.getTimeCount()));
        llMsgView.setMinimumWidth(getMinWidth(bean.getTimeCount()));
        String picUrl = StringUtils.appendPicPath(NetConfig.currentUser
                .getUserPic());
        Picasso.with(this)
                .load(picUrl)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(imgPic);

        voiceContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (currentId != bean.getMsgId()) {
                    currentId = bean.getMsgId();
                    // 播放录音
                    playVoice(bean.getMsgContent(), ivAnimation, false);
                } else if (currentId == bean.getMsgId()) {
                    if (null != mediaPlayer && mediaPlayer.isPlaying()) {
                        interruptVoicePlay();
                    } else {
                        currentId = bean.getMsgId();
                        // 播放录音
                        playVoice(bean.getMsgContent(), ivAnimation, false);
                    }
                }
            }
        });

        // 将消息添加到消息区
        llMsgContainer.addView(voiceContainer, index);
    }

    /**
     * 获取语音播放时长（采取进一位规则）
     * @param time 实际时长
     * @return 换算后的时长
     */
    private String getVoiceTime(long time) {
        double count = time / 1000f;
        //录音时长限制30秒，计时器有延时，会达到30-31秒之间，这时显示为30秒
        if (count > 30) {
            return String.valueOf((int) Math.floor(count)) + "\"";
        } else {
            return String.valueOf((int) Math.ceil(count)) + "\"";
        }
    }

    /**
     * 根据语音时长设置宽度
     * @param time 语音时长
     * @return 控件宽度
     */
    private int getMinWidth(long time) {
        int second = (int) Math.ceil(time / 1000f);
        // 超过20秒，控件宽度默认250dp
        if (second <= 20) {
            return DensityUtils.dp2px(ChatActivity.this, second * 10 + 40);
        } else {
            return DensityUtils.dp2px(ChatActivity.this, 250);
        }
    }

    /**
     * 播放语音
     * @param name 文件名
     * @param imageView 语音动画view
     * @param isLeft 发送者与接受者标识
     */
    private void playVoice(String name, ImageView imageView, boolean isLeft) {
        if (null == mediaPlayer) {
            mediaPlayer = new MediaPlayer();
        }
        playAudioAnimation(mediaPlayer, imageView, isLeft);
        try {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.reset();
            mediaPlayer.setDataSource(name);
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(
                    new MediaPlayer.OnCompletionListener() {

                        public void onCompletion(MediaPlayer mp) {

                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 添加图片消息显示到消息区
     * @param picFilePath 图片路径
     * @param index 索引
     */
    private void addMyPicMsgView(String picFilePath, int index) {
        View picContainer = getLayoutInflater().inflate(R.layout
                .view_msg_pic_me, null);

        // 头像
        ImageView imgPic = (ImageView) picContainer
                .findViewById(R.id.img_me_pic);
        String picUrl = StringUtils.appendPicPath(NetConfig.currentUser
                .getUserPic());
        Picasso.with(this)
                .load(picUrl)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(imgPic);
        LinearLayout.LayoutParams lp = new LinearLayout
                .LayoutParams(DensityUtils.dp2px(this, 130),
                DensityUtils.dp2px(this, 130));
        lp.topMargin = DensityUtils.dp2px(this, 5);
        lp.rightMargin = DensityUtils.dp2px(this, 5);
        lp.bottomMargin = DensityUtils.dp2px(this, 5);
        ImageView imgContent = (ImageView) picContainer
                .findViewById(R.id.img_pic_view);
        imgContent.setScaleType(ImageView.ScaleType.FIT_XY);
        ImageUtils imageUtils = new ImageUtils();
        Bitmap bitmap = imageUtils.ratio(picFilePath);
        bitmapArrayList.add(bitmap);
        imgContent.setLayoutParams(lp);
        imgContent.setImageBitmap(bitmap);
        final File file = new File(picFilePath);
        imgContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ChatActivity.this, PicViewActivity
                        .class);
                intent.putExtra(PIC_FILE, file);
                startActivity(intent);
            }
        });

        // 将消息添加到消息区
        llMsgContainer.addView(picContainer, index);
    }

    /**
     * 绑定消息发送按钮
     */
    private void bindSendMsgButtonEvent() {
        // 发送按钮事件
        btnSendMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String msg = etMsg.getText().toString();
                if (StringUtils.isNotEmpty(msg)) {
                    String msgSendDate = DateUtils.getStringDateFormat(new
                            Date(), DateUtils.yyyyMMddHHmmss);
                    String targetType = MqttMsgUtils.MSG_TARGET_TYPE_PERSONAL;

                    MqttMsgBean bean = new MqttMsgBean();
                    bean.setMsgContent(msg);
                    bean.setMsgSendDate(msgSendDate);
                    bean.setMsgTargetType(targetType);
                    bean.setMsgType(MqttMsgUtils.MSG_TYPE_TXT);
                    bean.setContact(NetConfig.currentUser.getUserId());
                    //bean.setIsRead("N");
                    bean.setTopicName(contactTopicName);

                    sendMsg(bean, TEXT);

                    // 清空输入框
                    etMsg.setText("");
                }
            }
        });
    }

    /**
     * mqtt广播接受者
     */
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                String msgString = intent.getStringExtra(EXTRA_MESSAGE);
                MqttMsgBean bean = JsonUtils.toEntity(msgString, MqttMsgBean.class);
                updateNoticeReadState();

                Message message = new Message();
                message.obj = bean;
                handler.sendMessage(message);
            }
        }
    };

    /**
     * 初始化消息回调
     */
    private void initMessageCallback() {
        this.mqttClient = MqttService.mqttClient;

        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BroadCastActions.ACTION_MESSAGE_RECEIVED);
        registerReceiver(receiver, intentFilter);
    }

    /**
     * 发送消息到MQTT服务器
     * @param mqttMsg 即时消息
     * @param type 类型
     */
    private void sendMsg(MqttMsgBean mqttMsg, int type) {
        if (RequestUtils.isNetworkConnected(this)) {
            //当网络连接的时候重新赋值
            mqttClient = MqttService.mqttClient;
        }

        if (mqttClient == null || !mqttClient.isConnected()) {
            if (mqttClient != null) {

            }
            Toast.makeText(this, getString(R.string.chat_unconnect), Toast.LENGTH_SHORT).show();
            return;
        }
        //非好友不能发送
        QueryBuilder qb = DatabaseHelper.getHelper(ChatActivity.this)
                .getRuntimeExceptionDao(RegisterUserNetBean.class)
                .queryBuilder();
        try {
            qb.where().eq("userName", mqttMsg.getTopicName())
                    .and()
                    .eq("ownerId", NetConfig.currentUser.getUserId());
            List<RegisterUserNetBean> users = qb.query();
            if (users.isEmpty()) {
                Toast.makeText(this, getString(R.string.chat_not_contact), Toast.LENGTH_SHORT)
                        .show();
                return;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            return;
        }
        try {
            mqttClient.publish(contactUserId, mqttMsg);
            showMsg(mqttMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示消息，储存消息
     * @param mqttMsg 消息实体
     */
    private void showMsg(MqttMsgBean mqttMsg) {

        // 添加时间线
        addTimeLine(new Date().getTime());

        // 发送消息后，更新最后时间标识
        lastTimeFlag = new Date().getTime();
        // 显示发送我的消息到消息区
        addMyMsgToForeground(mqttMsg);
        // 将消息写入数据库
        mqttMsg.setOwnerUserId(NetConfig.currentUser.getUserId());
        DatabaseHelper.getHelper(ChatActivity.this)
                .getRuntimeExceptionDao(MqttMsgBean.class)
                .create(mqttMsg);
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            MqttMsgBean mqttMsg = (MqttMsgBean) msg.obj;
            if (!(mqttMsg.getContact().equals(contactUserId) &&
                    mqttMsg.getTopicName().equals(NetConfig.currentUser.getUserName()))) {
                return;
            }

            // 添加时间线
            Date d = null;
            try {
                d = DateUtils.getDateFormat(mqttMsg.getMsgSendDate(), DateUtils
                        .yyyyMMddHHmmss);
            } catch (Exception e) {
                e.printStackTrace();
            }
            addTimeLine(d.getTime());

            // 添加消息到消息区
            addContactMsg(mqttMsg);

            // 收到消息后更新时间标识
            lastTimeFlag = new Date().getTime();

            updateNoticeReadState();
        }
    };

    /**
     * 在消息区追加一条当前用户发送文本的消息
     * @param msg 消息
     * @param index 索引
     */
    private void addMyTextMsgView(String msg, int index) {
        View v = getLayoutInflater().inflate(R.layout
                .view_msg_me, null);

        // 头像
        ImageView mePic = (ImageView) v.findViewById(R.id.img_me_pic);
        String picUrl = StringUtils.appendPicPath(NetConfig.currentUser
                .getUserPic());
        Picasso.with(this)
                .load(picUrl)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(mePic);

        SpannableString content = EmojiUtils.getExpressionString(this, msg);
        // 文本消息
        TextView txt = (TextView) v.findViewById(R.id.txt_msg_view);
        txt.append(content);
        // 将消息添加到消息区
        llMsgContainer.addView(v, index);
    }

    /**
     * 添加时间线
     * @param current 当前
     * @param index 索引
     */
    private void addTimeLine(long current, int index) {
        // 暂定消息时间线为60S
        if (Math.abs(current - lastTimeFlag) < 60000) {
            return;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日 HH:mm");
        Calendar calNow = Calendar.getInstance();
        Calendar cal1 = Calendar.getInstance();
        cal1.setTimeInMillis(current);
        if (calNow.get(Calendar.DAY_OF_YEAR) == cal1.get(Calendar.DAY_OF_YEAR)) {
            sdf = new SimpleDateFormat("HH:mm");
        }

        LinearLayout.LayoutParams params = new LinearLayout
                .LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 60);
        params.gravity = Gravity.CENTER;
        params.topMargin = 30;

        TextView txtTimeLine = new TextView(this);
        txtTimeLine.setBackgroundResource(R.drawable.bg_grey_round);
        txtTimeLine.setLayoutParams(params);
        txtTimeLine.setPadding(20, 0, 20, 0);
        txtTimeLine.setGravity(Gravity.CENTER);
        txtTimeLine.setTextSize(11);
        txtTimeLine.setTextColor(getResources().getColor(R.color.bg_normal));
        txtTimeLine.setText(sdf.format(current));

        llMsgContainer.addView(txtTimeLine, index);
        insertIndex++;
    }

    /**
     * 添加时间线到消息区底部
     * @param current 当前
     */
    private void addTimeLine(long current) {
        addTimeLine(current, -1);
    }

    /**
     * 在消息区追加一条好友文本消息
     * @param mqttMsg 信息
     * @param index 索引
     */
    private void addContactTextMsgView(final MqttMsgBean mqttMsg, int index) {
        View v = getLayoutInflater().inflate(R.layout.view_msg_contact, null);

        // 头像
        ImageView contactPic = (ImageView) v.findViewById(R.id.img_contact_pic);
        String picUrl = StringUtils.appendPicPath(contactPicPath);
        Picasso.with(this)
                .load(picUrl)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(contactPic);

        SpannableString content = EmojiUtils.getExpressionString(this, mqttMsg.getMsgContent());
        // 文本消息
        TextView txt = (TextView) v.findViewById(R.id.txt_msg_view);
        txt.append(content);
        // 将消息添加到消息区
        llMsgContainer.addView(v, index);
    }

    /**
     * 在消息区追加一条好友语音消息
     * @param mqttMsg 信息
     * @param index 索引
     */
    private void addContactVoiceMsgView(final MqttMsgBean mqttMsg, int index) {
        View voiceContainer = getLayoutInflater().inflate(R.layout
                .view_msg_voice_contact, null);

        // 头像
        ImageView imgPic = (ImageView) voiceContainer
                .findViewById(R.id.img_contact_pic);
        final View isRead = voiceContainer.findViewById(R.id.view_is_opened);
        LinearLayout llMsgView = (LinearLayout) voiceContainer.findViewById(R.id.ll_msg_view);
        TextView tvTimeCount = (TextView) voiceContainer.findViewById(R.id.tv_time_count);
        final ImageView ivAnimation = (ImageView) voiceContainer.findViewById(R.id.iv_animation);
        tvTimeCount.setText(getVoiceTime(mqttMsg.getTimeCount()));
        llMsgView.setMinimumWidth(getMinWidth(mqttMsg.getTimeCount()));
        if (mqttMsg.isRead()) {
            isRead.setVisibility(View.GONE);
        } else {
            isRead.setVisibility(View.VISIBLE);
        }
        String picUrl = StringUtils.appendPicPath(contactPicPath);
        Picasso.with(this)
                .load(picUrl)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(imgPic);

        voiceContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 播放录音
                if (currentId != mqttMsg.getMsgId()) {
                    mqttMsg.setRead(true);
                    RuntimeExceptionDao dao = DatabaseHelper.getHelper(ChatActivity.this)
                            .getRuntimeExceptionDao(MqttMsgBean.class);
                    dao.update(mqttMsg);
                    isRead.setVisibility(View.GONE);
                    currentId = mqttMsg.getMsgId();
                    playVoice(mqttMsg.getMsgContent(), ivAnimation, true);
                } else if (currentId == mqttMsg.getMsgId()) {
                    if (null != mediaPlayer && mediaPlayer.isPlaying()) {
                        interruptVoicePlay();
                    } else {
                        mqttMsg.setRead(true);
                        RuntimeExceptionDao dao = DatabaseHelper.getHelper(ChatActivity.this)
                                .getRuntimeExceptionDao(MqttMsgBean.class);
                        dao.update(mqttMsg);
                        isRead.setVisibility(View.GONE);
                        currentId = mqttMsg.getMsgId();
                        playVoice(mqttMsg.getMsgContent(), ivAnimation, true);
                    }
                }
            }
        });

        // 将消息添加到消息区
        llMsgContainer.addView(voiceContainer, index);
    }

    /**
     * 在消息区追加一条好友图片消息
     * @param picFilePath 路径
     * @param index 索引
     */
    private void addContactPicMsgView(String picFilePath, int index) {
        View picContainer = getLayoutInflater().inflate(R.layout
                .view_msg_pic_contact, null);

        // 头像
        ImageView imgPic = (ImageView) picContainer
                .findViewById(R.id.img_contact_pic);
        String picUrl = StringUtils.appendPicPath(contactPicPath);
        Picasso.with(this)
                .load(picUrl)
                .placeholder(R.drawable.pic_talkbox_sel)
                .error(R.drawable.pic_talkbox_sel)
                .into(imgPic);
        LinearLayout.LayoutParams lp = new LinearLayout
                .LayoutParams(DensityUtils.dp2px(this, 130),
                DensityUtils.dp2px(this, 130));
        lp.leftMargin = DensityUtils.dp2px(this, 5);
        lp.topMargin = DensityUtils.dp2px(this, 5);
        lp.bottomMargin = DensityUtils.dp2px(this, 5);
        ImageView imgContent = (ImageView) picContainer
                .findViewById(R.id.img_pic_view);
        imgContent.setScaleType(ImageView.ScaleType.FIT_XY);
        ImageUtils imageUtils = new ImageUtils();
        Bitmap bitmap = imageUtils.ratio(picFilePath);
        bitmapArrayList.add(bitmap);
        imgContent.setLayoutParams(lp);
        imgContent.setImageBitmap(bitmap);
        final File file = new File(picFilePath);
        imgContent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ChatActivity.this, PicViewActivity
                        .class);
                intent.putExtra(PIC_FILE, file);
                startActivity(intent);
            }
        });

        // 将消息添加到消息区
        llMsgContainer.addView(picContainer, index);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(receiver);
        super.onDestroy();
        if (bitmapArrayList.size() > 0) {
            for (int i = 0; i < bitmapArrayList.size(); i++) {
                Bitmap bitmap = bitmapArrayList.get(i);
                if (bitmap != null && !bitmap.isRecycled()) {
                    bitmap.recycle();
                    bitmap = null;
                }
            }
        }

        if (null != mediaPlayer && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer = null;
        }
        stopCountDown();
    }

    @Bind(R.id.img_volume)
    ImageView imgVolume; // 音量
    @Bind(R.id.ll_voice_popup)
    View llVoicePopup; // 录音显示UI层
    @Bind(R.id.ll_voice_recording)
    LinearLayout llVoiceRecording; // 录音状态UI容器
    @Bind(R.id.ll_voice_tooshort)
    LinearLayout llVoiceTooShort; // 录音时间太短UI容器

    private Handler mHandler = new Handler();
    private long startVoiceTime; // 开始录音时间
    private long endVoiceTime; // 结束录音时间
    private String voiceName; // 录音文件名
    private SoundMeter mSensor; // 录音工具类
    private static final int POLL_INTERVAL = 100; // 音量动画间隔

    /**
     * 音量动画更新线程
     */
    private Runnable mPollTask = new Runnable() {
        public void run() {
            double amp = mSensor.getAmplitude();
            updateVolumeDisplay(amp);
            mHandler.postDelayed(mPollTask, POLL_INTERVAL);
        }
    };

    /**
     * 启动录音
     * @param name 起点
     */
    private void start(String name) {
        mSensor.start(name);
        startCountDown();
        mHandler.postDelayed(mPollTask, POLL_INTERVAL);
    }

    /**
     * 停止录音
     * @param voiceName 声音
     */
    private void stop(String voiceName) {
        stopCountDown();
        mHandler.removeCallbacks(mPollTask);
        try {
            mSensor.stop(voiceName);

            String filePath = FileUtils.getSavePath(voiceName);
            File file = new File(filePath);
            if (file == null || !file.exists() || !file.isFile()) {
                ToastUtils.toastContent(this, getString(R.string.chat_recorde_failed));
                return;
            }
            if (file.length() == 0) {
                file.delete();
                ToastUtils.toastContent(this, getString(R.string.chat_recorde_failed));
                return;
            }

            if (endVoiceTime - startVoiceTime < 1000) {
                return;
            }

            String msgSendDate = DateUtils.getStringDateFormat(new
                    Date(), DateUtils.yyyyMMddHHmmss);
            String targetType = MqttMsgUtils.MSG_TARGET_TYPE_PERSONAL;
            long time = endVoiceTime - startVoiceTime;
            if (time > Constants.DEFAULT_MAX_RECORD_TIME) {
                time = Constants.DEFAULT_MAX_RECORD_TIME;
            }
            MqttMsgBean bean = new MqttMsgBean();
            bean.setMsgContent(filePath);
            bean.setMsgSendDate(msgSendDate);
            bean.setMsgTargetType(targetType);
            bean.setMsgType(MqttMsgUtils.MSG_TYPE_VOICE);
            bean.setContact(NetConfig.currentUser.getUserId());
            bean.setTopicName(contactTopicName);
            bean.setTimeCount(time);
            sendMsg(bean, VOICE);
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.toastContent(this, getString(R.string.chat_recorde_failed));
        }
    }

    /**
     * 刷新音量显示
     * @param signalEMA 音量
     */
    private void updateVolumeDisplay(double signalEMA) {

        switch ((int) signalEMA) {
            case 0:
            case 1:
                imgVolume.setImageResource(R.drawable.amp1);
                break;
            case 2:
            case 3:
                imgVolume.setImageResource(R.drawable.amp2);

                break;
            case 4:
            case 5:
                imgVolume.setImageResource(R.drawable.amp3);
                break;
            case 6:
            case 7:
                imgVolume.setImageResource(R.drawable.amp4);
                break;
            case 8:
            case 9:
                imgVolume.setImageResource(R.drawable.amp5);
                break;
            case 10:
            case 11:
                imgVolume.setImageResource(R.drawable.amp6);
                break;
            default:
                imgVolume.setImageResource(R.drawable.amp6);
                break;
        }
    }

    /**
     * 绑定声音事件
     */
    private void bindBtnVoiceEvent() {
        imgVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (btnVoice.getVisibility() == View.VISIBLE) {
                    btnVoice.setVisibility(View.GONE);
                    etMsg.setVisibility(View.VISIBLE);
                    imgVoice.setImageResource(R.drawable.ic_yuyinliaotian);
                } else {
                    btnVoice.setVisibility(View.VISIBLE);
                    etMsg.setVisibility(View.GONE);
                    imgVoice.setImageResource(R.drawable.ic_jianpan);
                }
            }
        });

        btnVoice.setOnTouchListener(new View.OnTouchListener() {
            //按下语音录制按钮时
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    if (null != mediaPlayer && mediaPlayer.isPlaying()) {
                        interruptVoicePlay();
                    }
                    // 修改按钮底色
                    btnVoice.setBackgroundResource(R.drawable.pic_talkbox_sel);

                    // 弹出音量消息提示UI
                    llVoicePopup.setVisibility(View.VISIBLE);
                    llVoiceRecording.setVisibility(View.VISIBLE);
                    llVoiceTooShort.setVisibility(View.GONE);

                    // 记录开始录音时间
                    startVoiceTime = System.currentTimeMillis();
                    // 文件名
                    voiceName = startVoiceTime + ".amr";
                    // 开始录音
                    start(voiceName);
                } else if (event.getAction() == MotionEvent.ACTION_UP) {
                    btnVoice.setBackgroundResource(R.drawable
                            .pic_talkingbox_nor);

                    // 记录录音截止时间
                    endVoiceTime = System.currentTimeMillis();
                    // 停止录音
                    stop(voiceName);
                    // 判断录音时间是否太短
                    if (endVoiceTime - startVoiceTime < 1000) {
                        llVoiceRecording.setVisibility(View.GONE);
                        llVoiceTooShort.setVisibility(View.VISIBLE);

                        mHandler.postDelayed(new Runnable() {
                            public void run() {
                                llVoiceTooShort.setVisibility(View.GONE);
                                llVoicePopup.setVisibility(View.GONE);
                            }
                        }, 1000);
                    } else {
                        llVoicePopup.setVisibility(View.GONE);
                    }
                }
                return true;
            }
        });
    }

    /**
     * 播放语音图标动画
     * @param mediaPlayer 语音播放器
     * @param imageView 图片
     * @param isLeft 语音发送与接收标识
     */
    private void playAudioAnimation(final MediaPlayer mediaPlayer, final ImageView imageView,
            boolean isLeft) {
        //定时器检查播放状态
        stopTimer();
        animationTimer = new Timer();
        //将要关闭的语音图片归位
        if (audioAnimationHandler != null) {
            Message msg = new Message();
            msg.what = 3;
            audioAnimationHandler.sendMessage(msg);
        }

        audioAnimationHandler = new AudioAnimationHandler(imageView, isLeft);
        timerTask = new TimerTask() {
            public boolean hasPlayed = false;

            @Override
            public void run() {
                if (mediaPlayer.isPlaying()) {
                    hasPlayed = true;
                    index = (index + 1) % 3;
                    Message msg = new Message();
                    msg.what = index;
                    audioAnimationHandler.sendMessage(msg);
                } else {
                    //当播放完时
                    Message msg = new Message();
                    msg.what = 3;
                    audioAnimationHandler.sendMessage(msg);
                    //播放完毕时需要关闭Timer等
                    if (hasPlayed) {
                        stopTimer();
                    }
                }
            }
        };
        //调用频率为500毫秒一次
        animationTimer.schedule(timerTask, 0, 500);
    }

    /**
     * 语音播放动画
     */
    class AudioAnimationHandler extends Handler {
        ImageView imageView;
        //判断是左对话框还是右对话框
        boolean isLeft;

        /**
         * 构造方法
         * @param imageView 图片view
         * @param isLeft 语音接收与发送标识
         */
        public AudioAnimationHandler(ImageView imageView, boolean isLeft) {
            this.imageView = imageView;
            //判断是左对话框还是右对话框
            this.isLeft = isLeft;
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //根据msg.what来替换图片，达到动画效果
            switch (msg.what) {
                case 0:
                    imageView.setImageResource(isLeft ? R.drawable.ic_yuyin_1 : R.drawable
                            .ic_yuyin_user_1);
                    break;
                case 1:
                    imageView.setImageResource(isLeft ? R.drawable.ic_yuyin_2 : R.drawable
                            .ic_yuyin_user_2);
                    break;
                case 2:
                    imageView.setImageResource(isLeft ? R.drawable.ic_yuyin : R.drawable
                            .ic_yuyin_user);
                    break;
                default:
                    imageView.setImageResource(isLeft ? R.drawable.ic_yuyin : R.drawable
                            .ic_yuyin_user);
                    break;
            }
        }
    }

    /**
     * 停止
     */
    private void stopTimer() {
        if (animationTimer != null) {
            animationTimer.cancel();
            animationTimer = null;
        }

        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    /**
     * 开始计时
     */
    private void startCountDown() {
        maxTimer = new Timer();
        maxTimerTask = new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        timeIndex++;
                        if (timeIndex >= 25 && timeIndex < 30) {
                            tvCountDown.setVisibility(View.VISIBLE);
                            tvCountDown.setText(appendTimeTip(countDown));
                            countDown--;
                        } else if (timeIndex >= 30) {
                            stop(voiceName);
                            llVoicePopup.setVisibility(View.GONE);
                        }
                    }
                });
            }
        };
        maxTimer.schedule(maxTimerTask, 1000, 1000);
    }

    /**
     * 停止计时
     */
    private void stopCountDown() {
        timeIndex = 0;
        countDown = 5;
        tvCountDown.setVisibility(View.INVISIBLE);
        if (null != maxTimer) {
            maxTimer.cancel();
            maxTimer = null;
        }

        if (null != maxTimerTask) {
            maxTimerTask.cancel();
            maxTimerTask = null;
        }
    }

    /**
     * 拼接倒计时提示
     * @param time 倒计时时间
     * @return 提示语
     */
    private String appendTimeTip(int time) {
        return getString(R.string.residue_time) + time + getString(R.string.second);
    }

    /**
     * 中断语音播放
     */
    private void interruptVoicePlay() {
        Message msg = new Message();
        msg.what = 3;
        audioAnimationHandler.sendMessage(msg);
        stopTimer();
        mediaPlayer.stop();
    }
}